<template>
  <div class="chat-window">
    <div class="chat-messages">
      <div v-for="(message, index) in messages" :key="index" class="message" :class="{'sent-container': message.from === 'sender1', 'received-container': message.from === 'sender2'}">
        <div :class="{'sent-container': message.from === 'sender1', 'received-container': message.from === 'sender2'}">
          <img :src="getAvatar(message.from)" alt="头像" class="avatar" :class="{'avatar-sent': message.from === 'sender1', 'avatar-received': message.from === 'sender2'}" />
          <p :class="{'sent-message': message.from === 'sender1', 'received-message': message.from === 'sender2'}">{{ message.content }}</p>
        </div>
      </div>
    </div>
    <ChatInput @new-message="addMessage" />
  </div>
</template>

<script>
import ChatInput from '@/components/ChatInput.vue'
import axios from 'axios'

export default {
  components: {
    ChatInput
  },
  data () {
    return {
      messages: []
    }
  },
  async created () {
    try {
      const response = await axios.get('/static/chat-history.json')
      this.messages = response.data.map((item) => ({
        type: item.type,
        from: item.type === 'received' ? 'sender2' : 'sender1',
        content: item.content
      }))
    } catch (error) {
      console.error('Error fetching chat history:', error)
    }
  },
  methods: {
    addMessage (newMessage) {
      this.messages.push({
        type: 'sent',
        from: 'sender1', // 假设当前用户是 sender1
        content: newMessage.content
      })
    },
    getAvatar (from) {
      return from === 'sender1'
        ? require('@/assets/avt-01.png')
        : require('@/assets/avt-02.png')
    }
  }
}
</script>

<style scoped>
.chat-window {
  height: 500px;
  border: 1px solid #ccc;
  border-radius: 5px;
  overflow: hidden;
}

.title {
  text-align: center;
  margin-bottom: 20px;
}

.chat-messages {
  padding: 10px;
  height: 420px;
  max-height: 500px;
  overflow-y: scroll;
}

.message {
  margin-top: 10px;
  display: flex;
  align-items: flex-start;
}

.sent-container {
  display: flex;
  justify-content: flex-end;
  align-items: flex-start;
}

.received-container {
  display: flex;
  justify-content: flex-start;
  align-items: flex-start;
}

.sent-message {
  background-color: #007bff;
  color: #fff;
  padding: 8px;
  border-radius: 8px;
  margin-right: 10px;
}

.received-message {
  background-color: #f0f0f0;
  padding: 8px;
  border-radius: 8px;
  margin-left: 10px;
}

.avatar {
  width: 30px;
  height: 30px;
  border-radius: 50%;
  margin-left: 10px;
  margin-right: 10px;
}

</style>
